package com.stridercheng.myjd.model;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;

import java.util.Stack;

/**
 * deiscription:
 * User: stridercheng
 * Date: 2015-07-09
 * Time: 19:12
 * FIXME
 */
public class AppManager {
    private static Stack<Activity> mActivityStack;
    private static AppManager appManager;

    public static AppManager getInstance() {
        if (appManager == null) {
            appManager = new AppManager();
        }

        return appManager;
    }

    public void addActivity(Activity activity) {
        if (mActivityStack == null) {
            mActivityStack = new Stack<Activity>();
        }

        mActivityStack.add(activity);
    }

    public Activity getTopActivity() {
        Activity activity = mActivityStack.lastElement();
        return activity;
    }

    public void killActivity(Activity activity) {
        if (activity != null) {
            mActivityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    public void killActivity(Class<?> cls) {
        for (Activity activity : mActivityStack) {
            if (activity.getClass().equals(cls)) {
                killActivity(activity);
            }
        }
    }

    public void killTopActivity() {
        Activity activity = mActivityStack.lastElement();
        killActivity(activity);
    }

    public void killAllActivity() {
        for (int i = 0, size = mActivityStack.size(); i < size; i++) {
            if (mActivityStack.get(i) != null) {
                mActivityStack.get(i).finish();
            }
        }
        mActivityStack.clear();
    }

    public void appExit(Context context) {
        killAllActivity();
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        manager.killBackgroundProcesses(context.getPackageName());
        System.exit(0);
    }
}
